package com.sgcc.sx.pmos.e_sx_mall.activity;


import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.sgcc.sx.pmos.common.base.MvpBaseActivity;
import com.sgcc.sx.pmos.common.bean.ComparisonDetailContentBean;
import com.sgcc.sx.pmos.common.bean.ComparisonDetailDataBean;
import com.sgcc.sx.pmos.common.bean.ComputationBean;
import com.sgcc.sx.pmos.common.bean.EventCenter;
import com.sgcc.sx.pmos.common.bean.PackageBean;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.widget.CustomizeHorizontalScrollView;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.e_sx_mall.adapter.ComparisonDetailContentAdapter;
import com.sgcc.sx.pmos.e_sx_mall.adapter.ComparisonDetailTopAdapter;
import com.sgcc.sx.pmos.e_sx_mall.bean.ComparisonDetailBackBean;
import com.sgcc.sx.pmos.e_sx_mall.contract.ComparisonDetailContract;
import com.sgcc.sx.pmos.e_sx_mall.presenter.ComparisonDetailPresenter;
import com.sgcc.sx.pmos.e_sx_mall.widget.OnStickyChangeListener;
import com.sgcc.sx.pmos.e_sx_mall.widget.StickyHeadContainer;
import com.sgcc.sx.pmos.e_sx_mall.widget.StickyItemDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ChaoAJ
 * @describe 对比详情
 * @time 2022/8/26 14:38
 */
public class ComparisonDetailActivity extends MvpBaseActivity<ComparisonDetailPresenter> implements ComparisonDetailContract.View, ComparisonDetailContentAdapter.OnTabScrollViewListener {


    private TitleBar mTitleBar;
    private Switch mSwitchComparisonDetailOptimal;
    private Switch mSwitchComparisonDetailHide;

    /**
     * 吸顶的title
     */
    private StickyHeadContainer shcTitleLayout;
    private TextView tvComparisonTitle;
    private TextView tvComparisonRightTitle;
    private ImageView imgIcon;


    /**
     * Tab栏ScrollView
     */
    private CustomizeHorizontalScrollView mHeadScrollView;
    /**
     * Tab栏RecyclerView
     */
    private RecyclerView mHeadRecyclerView;
    /**
     * 列表RecyclerView
     */
    private RecyclerView mContentRecyclerView;
    private ComparisonDetailContentAdapter comparisonDetailContentAdapter;
    private ComparisonDetailTopAdapter comparisonDetailTopAdapter;

    private LinearLayoutManager mContentLinearLayoutManager;
    private ArrayList<PackageBean> selectPackageList;
    private List<Integer> monthSelectIndexList = new ArrayList<>();
    private StickyItemDecoration stickyItemDecoration;

    private ComparisonDetailBackBean comparisonDetailBackBean;
    private ComparisonDetailDataBean comparisonDetailDataBean;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_comparison_detail;
    }

    @Override
    protected void initViews() {
        super.initViews();
        mTitleBar = findViewById(R.id.tv_comparisonDetail_title);
        shcTitleLayout = findViewById(R.id.shcTitleLayout);
        tvComparisonTitle = findViewById(R.id.tvComparisonTitle);
        tvComparisonRightTitle = findViewById(R.id.tvComparisonRightTitle);
        imgIcon = findViewById(R.id.imgIcon);
        mSwitchComparisonDetailOptimal = findViewById(R.id.switch_comparisonDetail_optimal);
        mSwitchComparisonDetailHide = findViewById(R.id.switch_comparisonDetail_hide);
        mHeadScrollView = findViewById(R.id.headScrollView);
        mHeadRecyclerView = findViewById(R.id.headRecyclerView);
        mContentRecyclerView = findViewById(R.id.contentRecyclerView);


    }

    @Override
    public boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        selectPackageList = (ArrayList<PackageBean>) intent.getSerializableExtra("selectPackageList");
        mTitleBar.setTitle("套餐综合对比");
        mTitleBar.setRightIcon(R.mipmap.go_main, view -> goMainActivity());
        // 设置RecyclerView水平显示
        mHeadRecyclerView.setLayoutManager(
                new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
        comparisonDetailTopAdapter = new ComparisonDetailTopAdapter();
        // 设置ListView禁止滑动，这样使得ScrollView滑动更流畅
        mHeadRecyclerView.setNestedScrollingEnabled(false);
        mHeadRecyclerView.setAdapter(comparisonDetailTopAdapter);
        mContentLinearLayoutManager = new LinearLayoutManager(this);
        mContentRecyclerView.setLayoutManager(mContentLinearLayoutManager);
        stickyItemDecoration = new StickyItemDecoration(shcTitleLayout, ComparisonDetailContentBean.TITLE);
        mContentRecyclerView.addItemDecoration(stickyItemDecoration);
        comparisonDetailContentAdapter = new ComparisonDetailContentAdapter();
        mContentRecyclerView.setAdapter(comparisonDetailContentAdapter);
        comparisonDetailContentAdapter.setOnTabScrollViewListener(this);

        for (PackageBean packageBean : selectPackageList) {
            monthSelectIndexList.add(0);
        }
        mPresenter.getComparisonDetailData(true, selectPackageList, monthSelectIndexList);

        initListener();

    }


    private void initListener() {

        mSwitchComparisonDetailHide.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (null != comparisonDetailBackBean)
                    if (b) {
                        List<ComparisonDetailContentBean> data = comparisonDetailContentAdapter.getData();
                        if (null != data && data.size() > 0) {
                            List<ComparisonDetailContentBean.ContentBean> contentList = data.get(1).getContentList();
                            if (null != contentList && contentList.size() > 1)
                                hintSameItem(data);
                        }


                    } else {
                        comparisonDetailContentAdapter.setList(comparisonDetailDataBean.getComparisonDetailContentBeans());

                    }

            }
        });

        tvComparisonRightTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startElectricityProportionActivity();
            }
        });

        comparisonDetailContentAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                startElectricityProportionActivity();
            }
        });


        stickyItemDecoration.setOnStickyChangeListener(new OnStickyChangeListener() {
            @Override
            public void onScrollable(int offset) {
                shcTitleLayout.scrollChild(offset);
                shcTitleLayout.setVisibility(View.VISIBLE);
            }

            @Override
            public void onInVisible() {
                shcTitleLayout.reset();
                shcTitleLayout.setVisibility(View.INVISIBLE);
            }
        });


        /**
         * Tab栏HorizontalScrollView水平滚动时，遍历所有RecyclerView列表，并使其跟随滚动
         */
        mHeadScrollView.setViewListener((l, t, oldl, oldt) -> {
            List<BaseViewHolder> baseViewHolders = comparisonDetailContentAdapter.getBaseViewHolders();
            for (BaseViewHolder viewHolder : baseViewHolders) {
                CustomizeHorizontalScrollView customizeHorizontalScrollView = viewHolder.getView(R.id.contentScrollView);
                customizeHorizontalScrollView.scrollTo(l, 0);
            }
        });

        /**
         * RecyclerView垂直滑动时，遍历更新所有item中HorizontalScrollView的滚动位置，否则会出现item位置未发生变化状态
         */
        mContentRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                List<BaseViewHolder> baseViewHolders = comparisonDetailContentAdapter.getBaseViewHolders();
                for (BaseViewHolder viewHolder : baseViewHolders) {
                    CustomizeHorizontalScrollView customizeHorizontalScrollView = viewHolder.getView(R.id.contentScrollView);
                    customizeHorizontalScrollView.scrollTo(comparisonDetailContentAdapter.getOffestX(), 0);
                }
            }
        });

        shcTitleLayout.setDataCallback(pos -> {
            List<ComparisonDetailContentBean> dataList = comparisonDetailContentAdapter.getData();
            if (dataList.size() > pos) {//吸顶title
                ComparisonDetailContentBean comparisonDetailContentBean = dataList.get(pos);
                tvComparisonTitle.setText(comparisonDetailContentBean.getTitleName());
                tvComparisonRightTitle.setText(comparisonDetailContentBean.getRightText());
                imgIcon.setImageResource(comparisonDetailContentBean.getIconRes());
            }
        });
    }

    @Override
    public void onEventMainThread(EventCenter eventCenter) {
        super.onEventMainThread(eventCenter);
        if (eventCenter.getEventCode() == ArguConstant.MONTH_REFRESH_CONTRAST) {//月份选择刷新
            String position = (String) eventCenter.getData();
            if (TextUtils.isEmpty(position))
                return;
            String[] split = position.split(",");

            monthSelectIndexList.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
            mPresenter.clearData();
            mPresenter.getComparisonDetailData(true, selectPackageList, monthSelectIndexList);

        } else if (eventCenter.getEventCode() == ArguConstant.REFRESH_ESTIMATED_PRICE) {//刷新预估价格数据
            List<ComputationBean.Bean> beanList = (List<ComputationBean.Bean>) eventCenter.getData();
            if (null != beanList && beanList.size() > 0) {
                List<ComparisonDetailContentBean> data = comparisonDetailContentAdapter.getData();
                for (ComparisonDetailContentBean datum : data) {
                    if (TextUtils.isEmpty(datum.getContentTitleName()))
                        continue;
                    if (datum.getContentTitleName().equals("商品")) {
                        List<ComparisonDetailContentBean.ContentBean> contentList = datum.getContentList();
                        for (int i = 0; i < contentList.size(); i++) {
                            for (ComputationBean.Bean bean : beanList) {
                                if (comparisonDetailBackBean.getPackageIdList().get(i).equals(bean.getPackageId())) {
                                    contentList.get(i).setText(bean.getPackagePrice());
                                }
                            }
                        }
                    }

                    if (datum.getContentTitleName().equals("基础价格套餐")) {
                        List<ComparisonDetailContentBean.ContentBean> contentList = datum.getContentList();
                        for (int i = 0; i < contentList.size(); i++) {
                            for (ComputationBean.Bean bean : beanList) {
                                if (comparisonDetailBackBean.getPackageIdList().get(i).equals(bean.getPackageId())) {
                                    contentList.get(i).setText(bean.getMainPrice());
                                }
                            }
                        }
                    }

                    if (datum.getContentTitleName().equals("浮动套餐")) {
                        List<ComparisonDetailContentBean.ContentBean> contentList = datum.getContentList();
                        for (int i = 0; i < contentList.size(); i++) {
                            for (ComputationBean.Bean bean : beanList) {
                                if (comparisonDetailBackBean.getPackageIdList().get(i).equals(bean.getPackageId())) {
                                    contentList.get(i).setText(bean.getFloPrice());
                                }
                            }
                        }
                    }

                }
                comparisonDetailContentAdapter.notifyDataSetChanged();
            }


        }


    }


    @Override
    public void querySuccess(ComparisonDetailBackBean comparisonDetailBackBean, ComparisonDetailDataBean comparisonDetailDataBean) {
        this.comparisonDetailBackBean = comparisonDetailBackBean;
        this.comparisonDetailDataBean = comparisonDetailDataBean;
        int width = 0;
        if (comparisonDetailDataBean.getComparisonDetailTopBeans().size() < 3)
            width = (ScreenUtils.getScreenWidth() - SizeUtils.dp2px(112)) / comparisonDetailDataBean.getComparisonDetailTopBeans().size();

        comparisonDetailTopAdapter.setItemWidth(width);
        comparisonDetailTopAdapter.setList(comparisonDetailDataBean.getComparisonDetailTopBeans());

        comparisonDetailContentAdapter.setItemWidth(width);
        comparisonDetailContentAdapter.setList(comparisonDetailDataBean.getComparisonDetailContentBeans());
    }

    @Override
    public void queryFailed() {

    }

    @Override
    protected ComparisonDetailPresenter createPresenter() {
        return new ComparisonDetailPresenter();
    }

    @Override
    public void scrollTo(int l, int t) {
        if (mHeadScrollView != null) {
            mHeadScrollView.scrollTo(l, 0);
        }
    }

    private void hintSameItem(List<ComparisonDetailContentBean> data) {
        List<ComparisonDetailContentBean> sameDataList = new ArrayList<>();
        for (ComparisonDetailContentBean datum : data) {
            List<ComparisonDetailContentBean.ContentBean> contentList = datum.getContentList();

            if (datum.getItemType() == ComparisonDetailContentBean.TITLE) {
                sameDataList.add(datum);
            } else {
                boolean isSame = true;
                for (int i = 1; i < contentList.size(); i++) {
                    ComparisonDetailContentBean.ContentBean contentBean = contentList.get(i - 1);
                    ComparisonDetailContentBean.ContentBean contentBean1 = contentList.get(i);
                    if (contentBean.getFlag() == contentBean1.getFlag()) {//-1 普通text  1 本地图片 2 套餐数据  9 选择套餐月份 下拉选择
                        if (contentBean1.getFlag() == -1)
//                            isSame = isSame && contentBean.getText().equals(contentBean1.getText());
                            isSame = isSame && TextUtils.equals(contentBean.getText(), contentBean1.getText());
                        if (contentBean1.getFlag() == 1)
                            isSame = isSame && contentBean.getImgRes() == contentBean1.getImgRes();
                        if (contentBean1.getFlag() == 2) {
//                            isSame = isSame && contentBean.getMealBean().getText1().equals(contentBean1.getMealBean().getText1())
//                                    && contentBean.getMealBean().getText2().equals(contentBean1.getMealBean().getText2());
                            isSame = isSame && TextUtils.equals(contentBean.getMealBean().getText1(), contentBean1.getMealBean().getText1())
                                    && TextUtils.equals(contentBean.getMealBean().getText2(), contentBean1.getMealBean().getText2());
                        }
                        if (contentBean1.getFlag() == 9) {
                            isSame = false;
                        }

                    } else {
                        isSame = false;
                    }


                }
                if (!isSame) {
                    sameDataList.add(datum);
                }
            }
        }

        comparisonDetailContentAdapter.setList(sameDataList);


    }

    private void startElectricityProportionActivity() {
//        if (UserManager.isLogin()) {
        int type = comparisonDetailBackBean.getType();
        Intent intent = new Intent(this, ElectricityProportionActivity.class);
        intent.putExtra("pageType", type);
        intent.putExtra("packageId", comparisonDetailBackBean.getPackageIdList());
        ActivityUtils.startActivity(intent);
//        } else {
//            UserManager.toLogin();
//        }


    }
}